package com.gary.shiro.util;

import java.security.MessageDigest;

/**
 * @author liliang
 * @date 2021/12/28
 **/
public class EncryptUtil {

    public static String md5Encrypt(String input) throws Exception{
        //创建消息摘要对象
        MessageDigest digest = MessageDigest.getInstance("MD5");
        //执行消息摘要算法
        byte[] bytes = digest.digest(input.getBytes()); //密文的byte数组
        //使用base64转码
        //return Base64.getEncoder().encodeToString(bytes);
        return toHex(bytes);
    }

    /**
     * 16进制转换
     * @param bytes
     * @return
     */
    private static String toHex(byte[] bytes){
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String s = Integer.toHexString(b & 0xff);
            //判断 如果密文长度是1 需要在高位进行补0
            if(s.length() == 1){
                s = "0" + s;
            }
            sb.append(s);
        }
        return sb.toString();
    }
}
